package org.esisar.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.esisar.model.Model;
import org.esisar.model.User;

public class UserStatementCreator implements StatementCreator{


	private PreparedStatement preparedStatement;
	
	@Override
	public PreparedStatement addStatement(Connection connection, Model model) throws SQLException {
		
		User user = modelToUser(model);
			
		preparedStatement = connection.prepareStatement("INSERT INTO client (idClient,email,name,surname,password) VALUES(client_sequence.nextval,?,?,?,?)");

		fillStatement(user);
	
		return preparedStatement;
		
	}

	@Override
	public PreparedStatement deleteStatement(Connection connection, List<Long> keys) throws SQLException {

		preparedStatement = connection.prepareStatement("DELETE FROM client WHERE id=?");

		preparedStatement.setLong(1, keys.get(0));
				
		return preparedStatement;
	}

	@Override
	public PreparedStatement updateStatement(Connection connection, Model model)
			throws SQLException {
		
		User user = modelToUser(model);
		
		preparedStatement = connection.prepareStatement("UPDATE user SET email = ?,name = ?, surname = ?,passwd = ?WHERE idClient = ?");

		fillStatement(user);
		preparedStatement.setLong(5, user.getIdClient());
		
		return preparedStatement;
	}

	private void fillStatement(User user) throws SQLException {
		preparedStatement.setString(1, user.getEmail());
		preparedStatement.setString(2, user.getName());
		preparedStatement.setString(3, user.getSurname());
		preparedStatement.setString(4, user.getPasswd());
	}

	private User modelToUser(Model model) {
		User user;
		
		if (model instanceof User){
			user = (User) model;
		}else{
			throw new ClassCastException("Bad object instance");
		}
		return user;
	}
	
	@Override
	public PreparedStatement readStatement(Connection connection, String field, String value) throws SQLException{
		
		preparedStatement = connection.prepareStatement("select * from client where " + field + " = ? ");

		preparedStatement.setString(1, value);
		
		return preparedStatement;
		
	}

	@Override
	public Model fillModel(ResultSet rs) throws SQLException {
		String email = rs.getString("email");
		String password = rs.getString("password");
		String idClient = rs.getString("idClient");
		String name = rs.getString("name");
		String surname = rs.getString("surname");
		
		User user = new User(email,name,surname,password);
		user.setIdClient(Long.parseLong(idClient));
		
		return user;
	}
	

}


